const router = require('koa-router')()
const fs = require('fs')
const path = require('path')

let deploy_html = path.join(__dirname, '../public/main/deploy.html')
let navgatio_html = path.join(__dirname, '../public/main/navagation.html')
let login_html = path.join(__dirname, '../public/auth/index.html')
let deploy_path = path.join(__dirname, '../modules.deploy.json')
let cofig_path = path.join(__dirname, '../modules.config.json')
// let business_file = path.join(__dirname, '../../business-servers')
// let base_file = path.join(__dirname, '../../base-servers')
// let project_file = path.join(__dirname, '../projects')
let data = ''

router.get('/', async (ctx, next) => {
  toRootPath(ctx)
  ctx.response.type = 'html'
  ctx.response.body = data
})
// 判断是否有生成文件 如果有走登陆 如果没走导航
const toRootPath = (ctx) => {
  if (fs.existsSync(deploy_path)) {
    // 如果这个文件存在代表已经配置完成
    let token = ctx.cookies.get('token')
    console.log(`----------token------------`, token)
    if (token) {
      data = fs.readFileSync(navgatio_html)
    } else {
      ctx.response.redirect('/auth/index.html#/')
    }
  } else {
    if (!fs.existsSync(cofig_path)) {
      // 执行生成modules.config.json文件
      // let business_dir = fs.readdirSync(business_file)
      let project_file = path.join(__dirname, '../projects')
      let project_dir = fs.readdirSync(project_file)
      let modules = []
      project_dir.map((f) => {
        let url = path.join(__dirname, `../projects/${f}/server/package.json`)
        if (fs.existsSync(url)) {
          let data = JSON.parse(fs.readFileSync(url).toString())
          modules.push({
            name: data.key,
            key: data.name,
            base: data.base,
            port: data.port
          })
        }
      })
      // base_dir.map((f) => {
      //   let url = path.join(__dirname, `../../base-servers/${f}/server/package.json`)
      //   if (fs.existsSync(url)) {
      //     let data = JSON.parse(fs.readFileSync(url).toString())
      //     modules.push({
      //       name: data.key,
      //       key: data.name,
      //       base: true,
      //       port: data.port
      //     })
      //   }
      // })
      fs.writeFileSync(cofig_path, JSON.stringify(modules))
      console.log('---success: 生成modules.config.json文件---', modules)
    }
    data = fs.readFileSync(deploy_html)
  }
}

module.exports = router
